﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Web.Mvc;

namespace Ornament.Web.Mvc
{

    #region

    #endregion

    /// <summary>
    /// 
    /// </summary>
    public class JsonContainerFilterAttribute : ActionFilterAttribute
    {
        /// <summary>
        /// </summary>
        public JsonContainerFilterAttribute()
        {
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="JsonContainerFilterAttribute"/> class. 
        /// </summary>
        /// <param name="parameterName">
        /// The name of action parameters.
        /// </param>
        public JsonContainerFilterAttribute(params string[] parameterName)
        {
            ParameterNames = parameterName;
            RequestFormKeys = parameterName;
        }

        /// <summary>
        /// Gets or sets the key from client submit.
        /// default same as <see cref="ParameterNames"/>
        /// </summary>
        public string[] RequestFormKeys { get; set; }

        /// <summary>
        /// Gets or sets ParameterNames which defined in Action Method in Mvc-Controller
        /// </summary>
        /// <value>
        /// The parameter name.
        /// </value>
        public string[] ParameterNames { get; set; }

        /// <summary>
        /// </summary>
        /// <param name="filterContext">
        /// The filter context.
        /// </param>
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (ParameterNames == null || ParameterNames.Length == 0)
            {
                MethodInfo actionMethod =
                    filterContext.Controller.GetType().GetMethod(filterContext.ActionDescriptor.ActionName);

                ParameterNames = (from parameterInfo in actionMethod.GetParameters()
                                  where parameterInfo.ParameterType == typeof (JsonContainer)
                                  select parameterInfo.Name).ToArray();
            }

            if (RequestFormKeys == null || RequestFormKeys.Length == 0)
            {
                RequestFormKeys = ParameterNames;
            }
            else if (RequestFormKeys.Length != ParameterNames.Length)
            {
                throw new ArgumentException("ParameterNames 与 RequestFormKeys 的数量不一致");
            }

            for (int i = 0; i < RequestFormKeys.Length; i++)
            {
                string formKey = RequestFormKeys[i];
                string s = filterContext.HttpContext.Request[formKey];
                filterContext.ActionParameters[ParameterNames[i]] = JsonContainer.Create(s);
            }
        }
    }
}